package com.lwl.leetcode;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author lwl
 * @Description TODO
 * @date 2023/7/25 0:18
 */
public class Code03LengthOfLongestSubstring {

    public static void main(String[] args) {
        System.out.println(lengthOfLongestSubstring("abcccabcbb"));
        System.out.println(lengthOfLongestSubstring("pwwkew"));
        System.out.println(lengthOfLongestSubstring("bbbbb"));
    }

    public static int lengthOfLongestSubstring(String s) {
        char[] charArray = s.toCharArray();
        int left = 0;
        int res = 0;
        Map<Character, Integer> charIndexMap = new HashMap<>();
        for (int right = 0; right < charArray.length; right++) {
            if (charIndexMap.containsKey(charArray[right])) {
                left = Math.max(left, charIndexMap.get(charArray[right]) + 1);
            }
            charIndexMap.put(charArray[right], right);
            res = Math.max(res, right - left + 1);
        }
        return res;
    }

    static public int lengthOfLongestSubstring2(String s) {
        if (s == null) {
            return 0;
        }
        char[] str = s.toCharArray();
        Set<Character> set = new HashSet<>();
        int left = 0;
        int res = 0;
        for (int i = 0; i < str.length; i++) {
            while (set.contains(str[i])) {
                set.remove(str[left++]);
            }
            set.add(str[i]);
            res = Math.max(res, i - left + 1);
        }
        return res;
    }

}
